use tauri::Manager;
use serde::{Deserialize, Serialize};

/// 屏幕信息
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ScreenInfo {
    /// 屏幕名称
    pub name: String,
    /// 屏幕尺寸
    pub size: (f64, f64),
    /// 屏幕位置
    pub position: (f64, f64),
    /// 缩放因子
    pub scale_factor: f64,
}

/// 获取当前鼠标所在屏幕的信息
#[tauri::command]
pub async fn get_current_screen(app: tauri::AppHandle) -> Result<ScreenInfo, String> {
    // 获取当前鼠标位置
    let mouse_pos = app.cursor_position()
        .map_err(|e| format!("获取鼠标位置失败: {}", e))?;
    
    // 获取所有显示器
    let monitors = app.available_monitors()
        .map_err(|e| format!("获取显示器列表失败: {}", e))?;
    
    // 查找鼠标所在的显示器
    for monitor in monitors {
        let position = monitor.position();
        let size = monitor.size();
        
        // 检查鼠标是否在这个显示器内
        if mouse_pos.x >= position.x as f64 
            && mouse_pos.x < (position.x + size.width as i32) as f64
            && mouse_pos.y >= position.y as f64 
            && mouse_pos.y < (position.y + size.height as i32) as f64 
        {
            return Ok(ScreenInfo {
                name: monitor.name().map(|s| s.to_string()).unwrap_or_else(|| "未知显示器".to_string()),
                size: (size.width as f64, size.height as f64),
                position: (position.x as f64, position.y as f64),
                scale_factor: monitor.scale_factor(),
            });
        }
    }
    
    // 如果没找到，返回主显示器
    if let Some(monitor) = app.available_monitors().ok().and_then(|m| m.into_iter().next()) {
        let position = monitor.position();
        let size = monitor.size();
        return Ok(ScreenInfo {
            name: monitor.name().map(|s| s.to_string()).unwrap_or_else(|| "主显示器".to_string()),
            size: (size.width as f64, size.height as f64),
            position: (position.x as f64, position.y as f64),
            scale_factor: monitor.scale_factor(),
        });
    }
    
    Err("无法获取任何显示器信息".to_string())
}

/// 在当前屏幕上居中显示窗口
/// 
/// # 参数
/// - `window`: 要居中的窗口
/// - `app`: 应用句柄
/// - `window_width`: 窗口宽度（逻辑像素）
/// - `window_height`: 窗口高度（逻辑像素）
fn center_window_on_current_screen(
    window: &tauri::WebviewWindow,
    app: &tauri::AppHandle,
    window_width: f64,
    window_height: f64,
) -> Result<(), String> {
    // 获取当前鼠标位置（物理像素）
    let mouse_pos = app.cursor_position()
        .map_err(|e| format!("获取鼠标位置失败: {}", e))?;
    
    // 获取所有显示器
    let monitors = app.available_monitors()
        .map_err(|e| format!("获取显示器列表失败: {}", e))?;
    
    // 查找鼠标所在的显示器
    for monitor in monitors {
        let position = monitor.position();
        let size = monitor.size();
        let scale_factor = monitor.scale_factor();
        
        // 检查鼠标是否在这个显示器内（物理像素坐标）
        if mouse_pos.x >= position.x as f64 
            && mouse_pos.x < (position.x + size.width as i32) as f64
            && mouse_pos.y >= position.y as f64 
            && mouse_pos.y < (position.y + size.height as i32) as f64 
        {
            // 将窗口的逻辑像素尺寸转换为物理像素
            let physical_window_width = window_width * scale_factor;
            let physical_window_height = window_height * scale_factor;
            
            // 计算居中位置（物理像素）
            let center_x = position.x as f64 + (size.width as f64 - physical_window_width) / 2.0;
            let center_y = position.y as f64 + (size.height as f64 - physical_window_height) / 2.0;
            
            // 设置窗口位置（物理像素）
            window.set_position(tauri::PhysicalPosition::new(center_x, center_y))
                .map_err(|e| format!("设置窗口位置失败: {}", e))?;
            
            return Ok(());
        }
    }
    
    // 如果没找到当前屏幕，使用默认居中
    // eprintln!("⚠️  未找到当前屏幕，使用默认居中");
    window.center()
        .map_err(|e| format!("居中窗口失败: {}", e))?;
    
    Ok(())
}

/// 创建翻译窗口
#[tauri::command]
pub async fn create_translate_window(app: tauri::AppHandle) -> Result<(), String> {
    if let Some(window) = app.get_webview_window("translate") {
        if let Ok(true) = window.is_focused() {
            return Ok(());
        } else {
            let _ = window.close();
        }
    }

    let window_width = 800.0;
    let window_height = 400.0;

    let window = tauri::WebviewWindowBuilder::new(
        &app,
        "translate",
        tauri::WebviewUrl::App("/#/translate".into())
    )
    .title("翻译")
    .inner_size(window_width, window_height)
    .visible(false) // 先隐藏，等设置位置后再显示
    .build()
    .map_err(|e| e.to_string())?;

    // 在当前屏幕上居中显示
    center_window_on_current_screen(&window, &app, window_width, window_height)?;

    window.show().map_err(|e| e.to_string())?;
    window.set_focus().map_err(|e| e.to_string())?;
    Ok(())
}

/// 创建设置窗口
#[tauri::command]
pub async fn create_setting_window(app: tauri::AppHandle) -> Result<(), String> {
    if let Some(window) = app.get_webview_window("setting") {
        if let Ok(true) = window.is_focused() {
            return Ok(());
        } else {
            let _ = window.close();
        }
    }

    let window_width = 800.0;
    let window_height = 600.0;

    let window = tauri::WebviewWindowBuilder::new(
        &app,
        "setting",
        tauri::WebviewUrl::App("/#/setting".into())
    )
    .title("设置")
    .inner_size(window_width, window_height)
    .visible(false) // 先隐藏，等设置位置后再显示
    .build()
    .map_err(|e| e.to_string())?;

    // 在当前屏幕上居中显示
    center_window_on_current_screen(&window, &app, window_width, window_height)?;

    window.show().map_err(|e| e.to_string())?;
    window.set_focus().map_err(|e| e.to_string())?;
    Ok(())
}

/// 显示主窗口
#[tauri::command]
pub async fn show_main_window(app: tauri::AppHandle) -> Result<(), String> {
    if let Some(main_window) = app.get_webview_window("main") {
        main_window.show().map_err(|e| e.to_string())?;
    }
    Ok(())
}

/// 关闭当前窗口
#[tauri::command]
pub async fn close_current_window(window: tauri::WebviewWindow) -> Result<(), String> {
    window.close().map_err(|e| format!("关闭窗口失败: {}", e))?;
    Ok(())
}

/// 移动窗口到指定位置
#[tauri::command]
pub async fn move_window(window: tauri::WebviewWindow, x: f64, y: f64) -> Result<(), String> {
    window.set_position(tauri::LogicalPosition::new(x, y))
        .map_err(|e| format!("移动窗口失败: {}", e))?;
    Ok(())
}

/// 读取文件并返回 base64 data URL
#[tauri::command]
pub async fn read_file_as_base64(file_path: String) -> Result<String, String> {
    use std::fs;
    use base64::engine::general_purpose;
    use base64::Engine;
    
    let file_data = fs::read(&file_path)
        .map_err(|e| format!("读取文件失败: {}", e))?;
    
    let base64_data = general_purpose::STANDARD.encode(&file_data);
    let data_url = format!("data:image/png;base64,{}", base64_data);
    
    Ok(data_url)
}

